package cron

import (
	"htgis/monitor/common/model"
	"htgis/monitor/module/agent/metric"
	"htgis/monitor/module/agent/util"
	"time"
)

// Collect data
func Collect() {
	transferConf := util.Config().Transfer
	if !transferConf.Enabled || len(transferConf.Addrs) == 0 {
		return
	}
	// 读取mapper中的FuncsAndInterval集,并通过不同的goroutine运行
	for _, v := range metric.Mappers {
		go collect(int64(v.Interval), v.Fs)
	}
}

// collect data every interval seconds
func collect(sec int64, funcs []func() []*model.MetricValue) {
	t := time.NewTicker(time.Second * time.Duration(sec)).C
	for {
		<-t
		hostname, err := util.Hostname()
		if err != nil {
			continue
		}
		metricValues := []*model.MetricValue{}
		ignoreMetrics := util.Config().IgnoreMetrics
		// execute every collector
		for _, f := range funcs {
			items := f()
			if items == nil || len(items) == 0 {
				continue
			}
			for _, mv := range items {
				if b, ok := ignoreMetrics[mv.Metric]; ok && b {
					continue
				} else {
					metricValues = append(metricValues, mv)
				}
			}
		}
		// set step, hostname, timestamp
		now := time.Now().Unix()
		for i := 0; i < len(metricValues); i++ {
			metricValues[i].Step = sec
			metricValues[i].Endpoint = hostname
			metricValues[i].Timestamp = now
		}
		// send metric values to transfer
		util.SendToTransfer(metricValues)
	}
}
